package com.liruo.learn.spring.mvc.enumconverter.api;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:liruo
 * @Date:2023-02-20-21:29:09
 * @Desc
 */
public abstract class AbstractEnumConverterFactory<V> implements EnumConverterFactory<V>{
    protected final EnumValueStrategy strategy;
    protected final Map<Integer, EnumConverter<V, ?>> cache = new ConcurrentHashMap<>();

    public AbstractEnumConverterFactory() {
        this.strategy = EnumValueStrategy.SOURCE;
    }
    public AbstractEnumConverterFactory(EnumValueStrategy strategy) {
        this.strategy = strategy;
    }


    public <E> EnumConverter<V, E> getConverter(Class<E> enumClazz){
        if(enumClazz == null){
            throw new NullPointerException("enumeration can't null");
        }
        int hash = enumClazz.getName().hashCode();
        if(cache.containsKey(hash)){
            return (EnumConverter<V, E>)cache.get(hash);
        }

        if(!enumClazz.isEnum()){
            throw new RuntimeException("enumeration can't extends twice other enumeration");
        }
        EnumConverter<V, Object> created = create(enumClazz);
        cache.put(hash, created);
        return (EnumConverter<V, E>)created;
    }
    protected abstract <E> EnumConverter<V, Object> create(Class<E> enumClazz);
}
